<?php
if (!class_exists('AlfaTranslator')) {

	/**
	 * Provides text translations
	 * @author Alecsandru Gabriel DINU
	 * @since Jun 25, 2008
	 */
	class AlfaTranslator {
	    private static $theInstance;
	    private static $ctx;
	    private static $messages;

	    private function __construct() {}

	    public static function getInstance() {
	        if (!self::$theInstance) {
	            self::$theInstance = new AlfaTranslator();
	        }
	        return self::$theInstance;
	    }

		/**
		 * Performs initialization.
		 * @access public
		 */
	    public function init(Context $context) {
 			$this->ctx = $context;
	        // load i8n data
	        $config = AlfaConfiguration::getInstance();
	        $messages_prefix = $config->getString("webapp/i18n-resources", "messages");
	        if ($this->ctx->getSession()->hasKey("_locale")) {
	        	include($messages_prefix . "_" . $this->ctx->getSession()->get("_locale") . ".properties.php");
	        } else {
	        	require($messages_prefix . ".properties.php");
	        }
	        $this->messages = $messages;

	    }

	    public function translate($params, &$ref ) {
			if(!empty($params['key'])) {
				return $this->message($params['key']);
			}
		  	return "";
	    }

		public function message($key) {
			$msg = "";
			if (array_key_exists($key, $this->messages)) {
				 $msg = $this->messages[$key];
			}

			if (StringUtils::isNotBlank($msg)) {
				return $msg;
			}
			return "??? $key ???";
		}


		/**
	     * Override clone method to throw exception
	     * @access public
	     * @return void
	     * @throws Exception
	     */
	    public function __clone() {
	    	throw new Exception('You cannot clone singleton object');
	    }
	}
}